package utils

import (
	"github.com/shopspring/decimal"
	"time"
)

type Finance struct {
	Tax         float64 `json:"tax" note:"税额"`
	NoTaxPrice  float64 `json:"no_tax_price" note:"不含税价格""`
	AvgDayPrice float64 `json:"avg_day_price" note:"日均收费"`
	Days        int64   `json:"days" note:"天数"`
}

var taxRate = 0.06

func CalculateFinance(days int64, payPrice float64) *Finance {
	noTaxPrice, _ := decimal.NewFromFloat(payPrice / (1 + taxRate)).Round(2).Float64()
	tax, _ := decimal.NewFromFloat(noTaxPrice * taxRate).Round(2).Float64()
	var avgDayPrice float64
	if days > 0 {
		avgDayPrice, _ = decimal.NewFromFloat(noTaxPrice / float64(days)).Round(2).Float64()
	} else {
		days = 0
	}
	finance := &Finance{
		Tax:         tax,
		NoTaxPrice:  noTaxPrice,
		AvgDayPrice: avgDayPrice,
		Days:        days,
	}
	return finance
}

// CalcServiceDays 计算指定年月服务天数
func CalcServiceDays(year, month int, vipStartTime time.Time, vipEndTime time.Time) float64 {
	if vipStartTime.After(vipEndTime) {
		return 0
	}
	// 月开始时间、月结束时间
	firstDay := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, vipStartTime.Location())
	endDay := time.Date(year, time.Month(month)+1, 0, 23, 59, 59, 999999999, vipStartTime.Location())
	if vipEndTime.Before(firstDay) {
		return 0
	}
	if vipStartTime.After(endDay) {
		return 0
	}
	if vipStartTime.After(firstDay) {
		firstDay = vipStartTime
	}
	if vipEndTime.Before(endDay) {
		endDay = vipEndTime
	}
	days, _ := decimal.NewFromFloat(endDay.Sub(firstDay).Hours() / 24).Round(2).Float64()
	return days
}
